package com.lt.lumentracks.controller.common;

import com.lt.lumentracks.context.BaseContext;
import com.lt.lumentracks.entity.vo.common.Result;
import com.lt.lumentracks.task.DynamicScheduledTask;
import com.lt.lumentracks.task.HotPostRefreshTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/common/task")
public class TaskController {

    @Autowired
    private DynamicScheduledTask dynamicScheduledTask;
    
    @Autowired
    private HotPostRefreshTask hotPostRefreshTask;
    private static final Map<Integer, Integer> DEGREE_SECONDS_MAP = Map.of(
            1, 2,
            2, 5,
            3, 10,
            4, 30,
            5, 60
    );


    /** 手动开启或关闭【最后消息刷新任务】定时任务
     * @param arg true:开启定时任务 false:关闭定时任务
     * @param degree 定时任务执行间隔程度。1-5，1级为2秒刷新一次，2级为5秒，3级为10秒，4级为30秒，5级为60秒，默认为程度2
     */
    @PostMapping("/lastMsg/startOrClose")
    public Result<String> lastMsgTask_startOrClose(@RequestParam Boolean arg, @RequestParam(defaultValue = "2") Integer degree) {
        Integer currentId = BaseContext.getCurrentId();
        if(currentId != 1){
            return Result.error("权限不足");
        }
        try{
            if(arg){
                Integer seconds = DEGREE_SECONDS_MAP.get(degree);
                if (seconds == null) {
                    return Result.error("参数错误");
                }
                dynamicScheduledTask.restartLastMsgTask(seconds);
            }else {
                Boolean cancelRes = dynamicScheduledTask.cancelLastMsgTask();
                if(!cancelRes){
                    log.warn("最后消息刷新任务操作警告：任务已经是关闭状态，请勿重复关闭");
                    return Result.error("最后消息刷新任务已经是关闭状态，请勿重复关闭");
                }
            }
        }catch (Exception e){
            log.error("最后消息刷新任务操作失败：{}", e.getMessage());
            return Result.error("最后消息刷新任务操作失败");
        }
        return Result.success();
    }


    /** 手动开启或关闭【热门帖子刷新任务】定时任务
     * @param arg true:开启定时任务 false:关闭定时任务
     * @param hours 定时任务执行间隔小时数，默认为3小时
     */
    @PostMapping("/hotPost/startOrClose")
    public Result<String> hotPostTask_startOrClose(@RequestParam Boolean arg, @RequestParam(defaultValue = "3") Integer hours) {
        Integer currentId = BaseContext.getCurrentId();
        if(currentId != 1){
            return Result.error("权限不足");
        }
        try{
            if(arg){
                if (hours <= 0) {
                    return Result.error("参数错误：间隔小时数必须大于0");
                }
                dynamicScheduledTask.restartHotPostTask(hours);
            }else {
                Boolean cancelRes = dynamicScheduledTask.cancelHotPostTask();
                if(!cancelRes){
                    log.warn("热门帖子刷新任务操作警告：任务已经是关闭状态，请勿重复关闭");
                    return Result.error("热门帖子刷新任务已经是关闭状态，请勿重复关闭");
                }
            }
        }catch (Exception e){
            log.error("热门帖子刷新任务操作失败：{}", e.getMessage());
            return Result.error("热门帖子刷新任务操作失败");
        }
        return Result.success();
    }



    /**
     * 手动刷新每日热门帖子数据（立即执行一次）
     */
    @PostMapping("/hotPost/refreshImmediately")
    public Result<String> refreshHotPostsImmediately() {
        Integer currentId = BaseContext.getCurrentId();
        if(currentId != 1){
            return Result.error("权限不足");
        }
        try {
            log.info("手动触发热门帖子数据刷新");
            hotPostRefreshTask.refreshHotPosts();
            return Result.success("热门帖子数据刷新成功");
        } catch (Exception e) {
            log.error("手动刷新热门帖子数据失败：{}", e.getMessage());
            return Result.error("热门帖子数据刷新失败：" + e.getMessage());
        }
    }



    /**
     * 获取定时任务状态
     */
    @PostMapping("/status")
    public Result<Map<String, Object>> getTaskStatus() {
        Integer currentId = BaseContext.getCurrentId();
        if(currentId != 1){
            return Result.error("权限不足");
        }
        try {
            Map<String, Object> status = dynamicScheduledTask.getTaskStatus();
            return Result.success(status);
        } catch (Exception e) {
            log.error("获取任务状态失败：{}", e.getMessage());
            return Result.error("获取任务状态失败");
        }
    }

}
